package com.yixin.hospital.utils;

import com.github.benmanes.caffeine.cache.Cache;
import com.yixin.hospital.common.Constant;
import com.yixin.hospital.entity.bo.UserDeptWorkAddressJobOffice;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.yixin.hospital.common.Constant.USER_CACHE;

@Component
public class CaffeineUtils {


    private static Cache<String, Object> userCaffeineCache;
    private static Cache<String, Object> userTokenCaffeineCache;

    @Resource
    public void setUserCaffeineCache(Cache<String, Object> userCaffeineCache) {
        CaffeineUtils.userCaffeineCache = userCaffeineCache;
    }

    @Resource
    public void setUserTokenCaffeineCache(Cache<String, Object> userTokenCaffeineCache) {
        CaffeineUtils.userTokenCaffeineCache = userTokenCaffeineCache;
    }

    public static void put(String key, Object value) {
        userCaffeineCache.put(key, value);
    }

    public static Object get(String key) {
        return userCaffeineCache.asMap().get(key);
    }

    public static UserDeptWorkAddressJobOffice getByUserId(Long userId) {
        List<UserDeptWorkAddressJobOffice> list = (List<UserDeptWorkAddressJobOffice>) get(USER_CACHE);
        if (CollectionUtils.isEmpty(list)) return null;
        Optional<UserDeptWorkAddressJobOffice> userOpt = list.stream().filter(user -> Objects.equals(user.getUserId(), userId)).findFirst();
        if (!userOpt.isPresent()) return null;
        return userOpt.get();
    }

    public static void putToken(String key, Object value) {
        userTokenCaffeineCache.put(key, value);
    }

    public static Object getToken(String key) {
        return userTokenCaffeineCache.asMap().get(key);
    }
}

